<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyWord" placeholder="员工姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getEmployees">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--员工信息显示列表-->
		<el-table :data="employees" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="username" label="员工姓名" width="120" sortable>
			</el-table-column>
			<el-table-column prop="age" label="员工年龄" width="120" sortable>
			</el-table-column>
			<el-table-column prop="shop.name" label="店铺" width="120" sortable>
			</el-table-column>
			<el-table-column prop="department.name" label="所属部门" width="120" sortable>
			</el-table-column>
			<el-table-column prop="email" label="邮箱" width="120" sortable>
			</el-table-column>
			<el-table-column prop="phone" label="联系方式" width="120" sortable>
			</el-table-column>
            <el-table-column prop="state" label="状态" width="100" sortable>
                <template scope="scope"> <!--显示状态信息-->
                    <span style="color: green" v-if="scope.row.state == 1">正常</span>
                    <span style="color: red" v-else-if="scope.row.state == -1">禁用</span>
                    <span v-else>未知</span>
                </template>
            </el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next"
						   @current-change="handleCurrentChange"
						   :page-size="pageSize"
						   :total="total"
						   style="float:right;">
			</el-pagination>
		</el-col>

		<!--添加、编辑界面-->
		<el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="员工姓名" prop="username">
					<el-input v-model="editForm.username" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="员工年龄" prop="age">
					<el-input v-model="editForm.age" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="editForm.email" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="联系方式" prop="phone">
					<el-input v-model="editForm.phone" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="editForm.password" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="1">正常</el-radio>
						<el-radio class="radio" :label="-1">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="店铺" prop="shop">
					 <!--elementUI中select选择器-->
					<!--value-key="id"：作为 :value 唯一标识的键名，绑定值为对象类型时必填-->
					<el-select v-model="editForm.shop" value-key="id" placeholder="请选择">
						<!--:key：对象的唯一标识-->
						<!--:label：选项的标签，若不设置则默认与 :value 相同-->
						<!--:value：选项的值，这里应该是一个对象-->
						<el-option
								v-for="item in shops"
								:key="item.id"
								:label="item.name"
								:value="item">
							<span style="float: left">{{ item.name }}</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{ item.tel}}</span>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="所属部门" prop="department">
					<!--:options：可选项数据源，键名可通过 :Props 属性配置-->
					<!--:props	配置选项-->
					<!--checkStrictly  是否严格的遵守父子节点不互相关联
						label	指定选项标签为选项对象的某个属性值
						value	指定选项的值为选项对象的某个属性值
					-->
					<el-cascader v-model="editForm.department"
							:options="tree"
							:props="{
								checkStrictly: true,
								label: 'name',
								value: 'id'
							}"
							clearable>
					</el-cascader>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getEmployeeListPage, removeEmployee, batchRemoveEmployee, editEmployee, addEmployee } from '../../api/api';

	export default {
		data() {
			return {
				filters: {
                    keyWord: ''
				},
				employees: [],
                shops: [],
                tree: [],
				total: 0,
                currentPage: 1,
				pageSize: 5,
				listLoading: false,
				sels: [],//列表选中列
                title: "",
				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					username: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//编辑界面数据
				editForm: {
				    id: null,
                    username: '',
                    age: '',
                    email: '',
                    phone: '',
                    password: '',
                    state: null,
                    department: null,
                    logininfo: null,
                    shop: null
				},

				editFormVisible: false,//新增界面是否显示
				addLoading: false,
				editFormRules: {
					username: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
			}
		},
		methods: {
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getEmployees();
			},
			//获取员工列表
			getEmployees() {
				let para = { // 分页+高级查询参数
					currentPage: this.currentPage,
					total: this.total,
					pageSize: this.pageSize,
                    keyWord: this.filters.keyWord // 高级查询参数
				};
				this.listLoading = true; // 忙等框开启
				/*发生post请求，分页请求，会被后端分页接口接收，并响应数据到result*/
				this.$http.post("/emp", para)
					.then(result=>{
					    this.employees = result.data.rows; // 填入分页数据
					    this.total = result.data.totals; // 填入数据总条数
                        this.listLoading = false; // 忙等框关闭
					}).catch(result=>{
					    console.debug(result)
						alert("系统繁忙")
				})
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => { // 发送请求成功时执行
					this.listLoading = true; // 忙等框
					// 携带参数发送删除请求，
					this.$http.delete("/emp/" + row.id)
						.then(result=>{ // 请求发送成功时执行
                            this.listLoading = false; // 关闭忙等框
                            // 根据后端响应的对象进行判断
						    if (result.data.success) { // 删除成功时执行
                                this.$message({ // elementui中消息框
                                    message: result.data.msg, // 获取后端响应的删除成功信息
                                    type: 'success'
                                });
							} else {
                                this.$message({ // elementui中消息框
                                    message: result.data.msg, // 获取后端响应的删除成功信息
                                    type: 'error'
                                });
							}
                            this.currentPage = 1; // 给当前页赋值
						    this.getEmployees(); // 加载数据，回到第一页
						}).catch(result=>{
                        this.$message({
                            message: "系统繁忙。。。。",
                            type: 'error'
                        });
					})
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
                this.title = "编辑";
                this.editFormVisible = true; // 显示模态框
                this.getTree(); // 调用获取员工树方法
                this.editForm = Object.assign({}, row); // 回显数据
			},
			//显示新增界面
			handleAdd: function () {
			    this.title = "新增";
                this.editFormVisible = true; // 显示模态框
                this.getTree();
                this.editForm = {
                    username: '',
                    age: '',
                    email: '',
                    phone: '',
                    password: '',
                    state: null,
                    department: null,
                    logininfo: null,
                    shop: null
				};
			},
			//编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true; // 按钮忙等框
							//NProgress.start();
							let para = Object.assign({}, this.editForm); // 克隆数据，将表单中的数据整合为一个对象
                            // 处理传输数据。----新增数据时上级员工使用
                            if (para.department) { // 当parent中有数据时执行
                                let p = para.department; // 获取parent中数据
                                let id = p[p.length - 1]; // 获取parent中最后一个数据
                                para.department = {"id" : id}; // 将数据封装成对象
                            }
							this.$http.put("/emp", para)
								.then(result=>{
                                    this.editFormVisible = false; // 成功与否都关闭模态框
                                    this.editLoading = false; // 成功与否都关闭按钮模态框
                                    if (result.data.success) {
                                        this.$message({
                                            message: '提交成功',
                                            type: 'success'
                                        });
									} else {
                                        this.$message({
                                            message: result.data.msg,
                                            type: 'error'
                                        });
									}
                                    this.getEmployees(); // 重新查询数据
								}).catch(result=>{
                                this.$message({
                                    message: "系统繁忙111111111。、。。。",
                                    type: 'error'
                                });
							})
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
			    // sels:数组，将选择的数据的id值取出封装为一个数组，并转换为String类型
                // var ids = this.sels.map(item => item.id).toString();

                var ids = this.sels.map(item => item.id) // sels:数组，将选择的数据的id值取出封装为一个数组
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true; // 开启忙等框
					this.$http.patch("/emp", ids)
						.then(result=>{
                            this.listLoading = false; // 关闭忙等框
							if (result.data.success) {
                                this.$message({
                                    message: result.data.msg,
                                    type: 'success'
                                });
							} else {
                                this.$message({
                                    message: result.data.msg,
                                    type: 'error'
                                });
							}
						}).catch(result=>{
                        this.$message({
                            message: "系统繁忙。。。",
                            type: 'error'
                        });
					})
				}).catch(() => {

				});
			},

            // 查询店铺
            getShops: function () {
                this.$http.get("/shop")
                    .then(result=>{
                       this.shops = result.data;
                    }).catch(result=>{
                        alert("获取shop失败")
                })
            },

            // 查询上级部门树
            getTree () {
                this.$http.get("/dept/tree")
                    .then(result=>{
                        this.tree = result.data;
                        console.debug(result.data)
                    }).catch(result=>{
                    alert("系统繁忙...")
                })
            }
		},
		mounted() {
			this.getEmployees();
			this.getShops();
		}
	}

</script>

<style scoped>

</style>